<template>
  <div>
    <!-- 三级分类全局组件 -->
    <Category :scene="scene" />
    <el-card class="margin-small">
      <!-- 平台属性列表 -->
      <div v-show="scene === 0">
        <el-button
          type="primary"
          size="default"
          icon="Plus"
          :disabled="!categoryStore.c3Id"
          @click="addAttr"
          >添加平台属性</el-button
        >
        <el-table class="margin-small" border :data="attrArr">
          <el-table-column
            type="index"
            label="序号"
            align="center"
            width="80px"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            align="center"
            width="120px"
            prop="attrName"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row }">
              <el-tag
                style="margin: 5px"
                v-for="item in row.attrValueList"
                :key="item.id"
                >{{ item.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180px">
            <template #="{ row }">
              <el-button
                type="warning"
                size="small"
                icon="Edit"
                @click="updateAttr(row)"
                >修改</el-button
              >
              <el-popconfirm
                :title="`确定删除${row.attrName}吗？`"
                width="200"
                @confirm="deleteAttr(row.id)"
              >
                <template #reference>
                  <el-button type="danger" size="small" icon="Delete"
                    >删除</el-button
                  >
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 展示添加属性和修改属性的结构 -->
      <div v-show="scene === 1">
        <!-- 展示添加属性和修改属性的结构 -->
        <el-form inline>
          <el-form-item label="属性名称">
            <el-input
              v-model="attrParams.attrName"
              placeholder="请输入属性名称"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          :disabled="!attrParams.attrName"
          type="primary"
          size="default"
          icon="Plus"
          @click="addAttrValue"
          >添加属性值</el-button
        >
        <el-table class="margin-small" border :data="attrParams.attrValueList">
          <el-table-column
            label="序号"
            width="80px"
            align="center"
            type="index"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row, $index }">
              <el-input
                :ref="(vc: any) => (inputArr[$index] = vc)"
                v-if="row.isEdit"
                size="small"
                v-model="row.valueName"
                placeholder="请输入属性值名称"
                @blur="toLook(row, $index)"
              ></el-input>
              <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="属性值操作" align="center" width="100px">
            <template #="{ $index }">
              <el-button
                type="danger"
                size="small"
                icon="Delete"
                @click="attrParams.attrValueList.splice($index, 1)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          size="default"
          @click="save"
          :disabled="!attrParams.attrValueList.length"
          >保存</el-button
        >
        <el-button size="default" @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { watch, ref, reactive, nextTick, onBeforeUnmount } from "vue";
// 引入获取已有属性与属性值的接口方法
import { reqAttr, reqAddOrUpdateAttr, reqDeleteAttr } from "@/api/product/attr";
import type {
  AttrResponseData,
  Attr,
  AttrValue,
} from "@/api/product/attr/type";
import useCategoryStore from "@/store/modules/category";
import { ElMessage } from "element-plus";
const categoryStore = useCategoryStore();
// 已有属性和属性值数组
const attrArr = ref<Attr[]>([]);
// 卡片显示与隐藏
const scene = ref<number>(0); // false 显示已有 true 显示添加与修改属性结构
// 收集新增的属性的数据
const attrParams = reactive<Attr>({
  attrName: "",
  attrValueList: [],
  categoryId: "",
  categoryLevel: 3,
});
// 存储对应的组件实例el-input
const inputArr = ref<any>([]);

// 监听仓库三级分类 id 变化
watch(
  () => categoryStore.c3Id,
  async () => {
    attrArr.value = [];
    if (!categoryStore.c3Id) return;
    getAttr();
  },
);

// 获取已有属性与属性值的方法
const getAttr = async () => {
  // 获取分类的id
  const { c1Id, c2Id, c3Id } = categoryStore;
  const result: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id);
  if (result.code === 200) {
    attrArr.value = result.data;
  }
};

// 添加属性按钮的回调
const addAttr = () => {
  // 每次点击先清空数据，在收集数据
  Object.assign(attrParams, {
    attrName: "",
    attrValueList: [],
    categoryId: categoryStore.c3Id,
    categoryLevel: 3,
  });
  // 切换为添加与修改属性的结构
  scene.value = 1;
};

// 表格中修改已有属性按钮的回调
const updateAttr = (row: Attr) => {
  // 切换为添加与修改属性的结构
  scene.value = 1;
  // 将已有的属性对象赋值给属性参数对象
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)));
};

// 取消按钮的回调
const cancel = () => {
  // 切换为添加与修改属性的结构
  scene.value = 0;
};

// 添加属性值按钮的回调
const addAttrValue = () => {
  // 点击按钮，像数组添加属性值对象
  attrParams.attrValueList.push({
    valueName: "",
    isEdit: true, // 标识是否是编辑状态
  });
  // 获取最后的el-input组件，聚焦
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus();
  });
};

// 保存按钮的回调
const save = async () => {
  const result: any = await reqAddOrUpdateAttr(attrParams);
  // 添加属性或者修改已有属性成功
  if (result.code === 200) {
    // 切换场景
    scene.value = 0;
    // 提示信息
    ElMessage({
      type: "success",
      message: attrParams.id ? "修改成功" : "添加成功",
    });
    // 刷新已有的属性和属性值
    getAttr();
  } else {
    ElMessage({
      type: "error",
      message: attrParams.id ? "修改失败" : "添加失败",
    });
  }
};

// 属性值输入框失去焦点的回调
const toLook = (row: AttrValue, $index: number) => {
  // 非法情况的判断
  if (row.valueName.trim() === "") {
    // 删除对应的属性值为空的元素
    attrParams.attrValueList.splice($index, 1);
    // 提示信息
    ElMessage({
      type: "error",
      message: "属性值名称不能为空",
    });
    return;
  }
  const repeat = attrParams.attrValueList.find((item) => {
    // 去掉当前失去焦点的属性值对象
    if (item != row) {
      return item.valueName === row.valueName;
    }
  });
  if (repeat) {
    // 删除对应的重复属性值的元素
    attrParams.attrValueList.splice($index, 1);
    // 提示信息
    ElMessage({
      type: "error",
      message: "属性值已存在",
    });
    return;
  }
  row.isEdit = false;
};

// 属性值点击的回调
const toEdit = (row: AttrValue, $index: number) => {
  row.isEdit = true;
  // 响应式数据发生变化，获取更新后的DOM（组件实例）
  nextTick(() => {
    inputArr.value[$index].focus();
  });
};

// 删除已有属性的方法回调
const deleteAttr = async (attrId: number) => {
  const result: any = await reqDeleteAttr(attrId);
  if (result.code === 200) {
    getAttr();
    ElMessage({
      type: "success",
      message: "删除成功",
    });
  } else {
    ElMessage({
      type: "error",
      message: "删除失败",
    });
  }
};

// 组件销毁前，清空分类仓库中数据
onBeforeUnmount(() => {
  // 仓库方法 $reset() 重置仓库中的数据
  categoryStore.$reset();
});
</script>

<style scoped lang="scss">
.margin-small {
  margin: 10px 0;
}
</style>
